package com.epro.dx.activity.creditcard;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.PaymentCompleteActivity;
import com.epro.dx.adapter.ChooseYearMonthListAdapter;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.CreditCardCheckUtils;
import com.epro.dx.util.CreditCardCheckUtils.CardType;
import com.epro.dx.util.DpPxUtils;
import com.epro.dx.widget.DataYearOrMonthPickerDialog;
import com.epro.dx.widget.TakePhotoPopWin;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.CreditCardLogoModel;
import com.weipu.common.facade.model.CreditCardModel;
import com.weipu.common.facade.model.CreditCardPayRespose;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.SecurityUtil;

/**
 * 新增信用卡页面
 * */
public class AddCreditCardActivity extends BaseFragmentActivity implements
		OnClickListener {
	private static final String TAG = "AddCreditCardActivity";
	// 卡信息部分
	private EditText cardNumber;
	private EditText isSuingBank;
	private EditText expirationMoth;
	private EditText expirationYear;
	private EditText securityCode;

	private TextView cardNumberTitle;

	private TextView expirationTitle;
	private TextView billingAddressTitle;

	private LinearLayout issuingBankLayout;
	// 账单地址部分
	private RelativeLayout billingAddress;
	private TextView name;
	private TextView address;

	// 支付按钮
	private Button payButton;

	// 是否添加卡片复选框
	private CheckBox isAddCard;

	// PCI图片
	private ImageView pciImage;

	private ImageView securityCodeHelp;

	private LinearLayout pciLink;

	private TextView pciContent;

	private String creditCardNumber;

	private GridView iconGridView;

	private AlertDialog securityCodeDialog;

	private int[] iconId = { R.drawable.visa_icon, R.drawable.msater_card_icon,
			R.drawable.american_express_icon, R.drawable.discover_icon,
			R.drawable.diners_club_icon, R.drawable.jcb_icon };
	private int[] iconOnId = { R.drawable.visa_icon_on,
			R.drawable.msater_card_on, R.drawable.american_express_icon_on,
			R.drawable.discover_icon_on, R.drawable.diners_club_icon_on,
			R.drawable.jcb_icon_on };

	private List<CreditCardLogoModel> ccLogos = new ArrayList<CreditCardLogoModel>();

	private int lightIconIndex;

	private IconAdapter iconAdapter;

	private String cardFlow = "EGP";

	private TakePhotoPopWin takePhotoPopWin;

	private ArrayList<String> monthList = new ArrayList<String>();
	private ArrayList<String> yearList = new ArrayList<String>();

	private AddressModel.Address myAddress = null;

	private boolean isCardValid = false;

	private String orderNumber = null;

	private CardType cardType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_creditcard_add);
		setTitleContent(R.string.creditcard_add_pagename).setFocusable(false);
		Intent intent = getIntent();
		if (null != intent) {
			cardFlow = intent.getStringExtra("CardFlow");
			orderNumber = intent
					.getStringExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER);
			lines = intent.getParcelableArrayListExtra("Lines");
			couponCode = intent.getStringExtra("CouponCode");
			fromPage = intent.getStringExtra("fromPage");
		}
		setDateTextList();
		initView();
		setEvent();
	}

	@Override
	protected void onResume() {
		super.onResume();
		sendScreen();
	}

	/**
	 * 设置日期文本列表
	 */
	private void setDateTextList() {
		yearList.clear();
		monthList.clear();
		// 设置月份列表
		for (int i = 0; i < 12; i++) {
			if (i < (10 - 1)) {
				monthList.add("0" + (i + 1));
			} else {
				monthList.add("" + (i + 1));
			}
		}
		// 设置年份列表
		// 获取当前年份
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String str = formatter.format(curDate);
		int currentYear = Integer.parseInt(str);
		for (int i = 0; i < 10; i++) {
			yearList.add("" + (currentYear + i));
		}
	}

	private void setCreditCardLogoModel() {
		for (int i = 0; i < iconId.length; i++) {
			CreditCardLogoModel model = new CreditCardLogoModel();
			model.setDrawableId(iconId[i]);
			ccLogos.add(model);
		}
	}

	// 加载视图控件
	private void initView() {
		setLeftBtnContent(true, -1);
		String carNoTitle = "<font color='#CA4341'>" + "*" + "</font>"
				+ getResources().getString(R.string.card_number);
		String expirTitle = "<font color='#CA4341'>" + "*" + "</font>"
				+ getResources().getString(R.string.expiration_month_year);
		String billTitle = "<font color='#CA4341'>" + "*" + "</font>"
				+ getResources().getString(R.string.billing_address_title);

		cardNumberTitle = (TextView) findViewById(R.id.card_number_title);
		cardNumberTitle.setText(Html.fromHtml(carNoTitle));
		expirationTitle = (TextView) findViewById(R.id.expiration_title);
		billingAddressTitle = (TextView) findViewById(R.id.billing_address_title);
		expirationTitle.setText(Html.fromHtml(expirTitle));
		billingAddressTitle.setText(Html.fromHtml(billTitle));
		cardNumber = (EditText) findViewById(R.id.creditcart_add_cardnumber);
		// cardNumber.showType = true;
		bankCardNumAddSpace(cardNumber);
		// cardNumber.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
		// cardNumber.setPattern(new int[] { 4, 4, 4, 4 });
		// cardNumber.setSeparator(" ");
		isSuingBank = (EditText) findViewById(R.id.creditcart_add_issuingbank);
		issuingBankLayout = (LinearLayout) findViewById(R.id.issuing_bank_layout);
		expirationMoth = (EditText) findViewById(R.id.creditcart_add_validtime_month);
		expirationYear = (EditText) findViewById(R.id.creditcart_add_validtime_year);
		securityCode = (EditText) findViewById(R.id.creditcart_add_seculity_code);
		hideSoftInputMethod(securityCode);
		billingAddress = (RelativeLayout) findViewById(R.id.creditcart_add_billing_address);
		name = (TextView) findViewById(R.id.creditcart_add_billing_address_name);
		name.setText(R.string.fill_billing_address);
		address = (TextView) findViewById(R.id.creditcart_add_billing_address_text);
		address.setVisibility(View.GONE);
		payButton = (Button) findViewById(R.id.creditcart_add_bt_pay);

		isAddCard = (CheckBox) findViewById(R.id.creditcart_add_cb_addcard);
		pciContent = (TextView) findViewById(R.id.pci_description);
		pciImage = (ImageView) findViewById(R.id.creditcart_add_pci);
		pciLink = (LinearLayout) findViewById(R.id.pci_link);
		iconGridView = (GridView) findViewById(R.id.credit_card_icon);
		setViewVisiable();
		setCreditCardLogoModel();
		iconAdapter = new IconAdapter();
		iconGridView.setAdapter(iconAdapter);
	}

	// 设置控件的事件️监听
	private void setEvent() {
		// // 返回按钮
		// backButton.setOnClickListener(this);
		cardNumber.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable a) {
				// if()
				String currStr = a.toString();
				creditCardNumber = currStr.replaceAll(" ", "");
				// creditCardNumber = cardNumber.getNonSeparatorText();
				if (creditCardNumber.length() >= 12) {
					cardType = CreditCardCheckUtils
							.getBankCardType(creditCardNumber, false,
									AddCreditCardActivity.this);
					setCardIconLight(cardType);
				}
			}
		});

		cardNumber.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean focused) {
				if (!focused) {
					checkCardType();
				}

			}
		});

		securityCode.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean isForcus) {
				if (isForcus) {
					securityCode.setSelection(securityCode.length());
					showPopFormBottom();
//					new Handler().postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//							imm.hideSoftInputFromWindow(
//									securityCode.getWindowToken(), 0);
//						}
//					}, 20);

				}

			}
		});
		securityCode.setOnClickListener(this);
		//
		// 点击pci图片显示PCI详情图片
		pciImage.setOnClickListener(this);

		// 点击提交支付按钮
		payButton.setOnClickListener(this);

		// 点击账单地址框进入账单地址编辑页
		billingAddress.setOnClickListener(this);
		expirationYear.setOnClickListener(this);
		expirationMoth.setOnClickListener(this);
		pciLink.setOnClickListener(this);
		findViewById(R.id.item_creditcard_security_code_help)
				.setOnClickListener(this);
		topbarLeftTv.setOnClickListener(this);
	}

	private void setViewVisiable() {
		if ("EGP".equals(cardFlow)) {
			issuingBankLayout.setVisibility(View.GONE);
			pciContent.setVisibility(View.VISIBLE);
		} else {
			issuingBankLayout.setVisibility(View.VISIBLE);
			pciContent.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (null != data) {
			addressModel = (AddressModel) data
					.getSerializableExtra("addressModel");
			refreshAddress(addressModel);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void refreshAddress(AddressModel addModel) {
		if (null == addModel) {
			return;
		}
		myAddress = addModel.getAddress();
		if (null != address) {
			// 收获人姓名
			name.setText(myAddress.getFirstName() + ","
					+ myAddress.getLastName());
			StringBuilder getProductAddress = new StringBuilder();
			String street2 = myAddress.getStreet2();
			if (null != street2 && !"".equals(street2)) {
				getProductAddress.append(street2).append(",");
			}
			getProductAddress.append(myAddress.getStreet1()).append(",")
					.append(myAddress.getCity()).append(",")
					.append(myAddress.getState()).append(",")
					.append(addModel.getCountryName()).append("(")
					.append(myAddress.getPostalCode()).append(")");
			// 收货地址
			address.setText(getProductAddress);
			address.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.creditcart_add_billing_address:// 进入账单地址编辑页
			Intent i = new Intent(AddCreditCardActivity.this,
					BillingAddressActivity.class);
			if (null != addressModel) {
				i.putExtra("AddressModel", addressModel);
			}
			startActivityForResult(i, 1);
			break;
		case R.id.creditcart_add_pci:// 显示pci详情页
		case R.id.pci_link:
			Intent pciIntent = new Intent(AddCreditCardActivity.this,
					CreditCardPciActivity.class);
			startActivity(pciIntent);
			break;
		case R.id.creditcart_add_bt_pay:// 执行信用卡校验及支付逻辑
			checkAndPay();
			break;
		case R.id.topbar_left_tv:// 返回上一个页面
			if (null != fromPage && "toPay".equals(fromPage)) {
				showConfirmGiveUpPayDialog();
			} else {
				finish();
			}
			break;
		case R.id.creditcart_add_validtime_year:
			// showDateYearDialog("year!", true);
			checkCardType();
			if (isCardValid) {
				showChooseDateDialog(true);
			}
			break;
		case R.id.creditcart_add_validtime_month:
			// showDateYearDialog("month!", false);
			checkCardType();
			if (isCardValid) {
				showChooseDateDialog(false);
			}
			break;
		case R.id.item_creditcard_security_code_help:
			Intent intent = new Intent(AddCreditCardActivity.this,
					SecurityCodeHelpActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.scale_in, R.anim.alpha_out);
			break;
		case R.id.creditcart_add_seculity_code:
			// // showSecurityCodeDialog();
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(securityCode.getWindowToken(), 0);
			showPopFormBottom();
			break;
		default:
			break;
		}
	}

	public void showPopFormBottom() {
		if (!isFinishing()) {
			takePhotoPopWin = new TakePhotoPopWin(this, securityCode);
			takePhotoPopWin.setFocusable(false);
			// showAtLocation(View parent, int gravity, int x, int y)
			takePhotoPopWin.showAtLocation(AddCreditCardActivity.this
					.findViewById(R.id.creditcart_add_seculity_code),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}
	}

	/**
	 * 校验信用卡卡号
	 */
	private void checkCardType() {
		if (null == creditCardNumber || "".equals(creditCardNumber)) {
			isCardValid = false;
			showToast(AddCreditCardActivity.this
					.getString(R.string.creditcard_no_card_number));
			return;
		}
		CardType cardType = CreditCardCheckUtils.getBankCardType(
				creditCardNumber, false, AddCreditCardActivity.this);
		switch (cardType) {
		case MasterCard:
		case VISA:
		case DinersClub:
		case Discover:
		case AmericanExpress:
		case JCB:
			isCardValid = true;
			break;
		case Unknown:// 无效卡号
			isCardValid = false;
			showToast(AddCreditCardActivity.this
					.getString(R.string.invalid_card_sug));
			break;

		default:// 不支持的卡类型
			isCardValid = false;
			showToast(AddCreditCardActivity.this
					.getString(R.string.creditcard_not_surpport_card));
			break;
		}
	}

	/**
	 * 校验并执行支付逻辑
	 */
	private void checkAndPay() {
		// 信用卡号
		checkCardType();
		if (!isCardValid) {
			return;
		}
		// 有效期
		if (TextUtils.isEmpty(expirationMoth.getText().toString())
				|| TextUtils.isEmpty(expirationYear.getText().toString())) {
			showToast(AddCreditCardActivity.this
					.getString(R.string.creditcard_no_expiration));
			return;
		}
		// 安全码
		if (TextUtils.isEmpty(securityCode.getText().toString())) {
			showToast(AddCreditCardActivity.this
					.getString(R.string.creditcard_no_security_code));
			return;
		}
		// 账单地址
		if (null == myAddress) {
			showToast(AddCreditCardActivity.this
					.getString(R.string.creditcard_no_billing_address));
			return;
		}

		// 执行支付逻辑
		goToPay();
	}

	/**
	 * 整合参数执行支付
	 */
	private void goToPay() {
		// 信用卡信息
		CreditCardModel creditCardModel = new CreditCardModel();
		creditCardModel.setCardNumber(creditCardNumber);
		creditCardModel.setExpireMonth(expirationMoth.getText().toString());
		creditCardModel.setExpireYear(expirationYear.getText().toString());
		String securityCodeStr = securityCode.getText().toString();
		try {
			securityCodeStr = SecurityUtil.aesEncrypt(securityCodeStr);
		} catch (Exception e) {
			// 加密异常
			securityCodeStr = securityCode.getText().toString();
		}
		creditCardModel.setCVVCode(securityCodeStr);
		creditCardModel.setCardHolder(myAddress.getFirstName() + " "
				+ myAddress.getLastName());

		AsyncTaskUtil.executeTask(new PayTask(creditCardModel));
	}

	/**
	 * 根据不同卡类型 高亮显示卡Logo
	 * 
	 * @param cardType
	 */
	private void setCardIconLight(CardType cardType) {
		ccLogos.get(lightIconIndex).setSelected(false);
		switch (cardType) {
		case Unknown:
			break;
		case MasterCard:
			ccLogos.get(1).setSelected(true);
			lightIconIndex = 1;
			break;
		case VISA:
			ccLogos.get(0).setSelected(true);
			lightIconIndex = 0;
			break;
		case AmericanExpress:
			ccLogos.get(2).setSelected(true);
			lightIconIndex = 2;
			break;
		case UnionPay:
			break;
		case DinersClub:
			ccLogos.get(4).setSelected(true);
			lightIconIndex = 4;
			break;
		case enRoute:
			break;
		case Discover:
			ccLogos.get(3).setSelected(true);
			lightIconIndex = 3;
			break;
		case JCB:
			ccLogos.get(5).setSelected(true);
			lightIconIndex = 5;
			break;
		case Laser:
			break;
		case Maestro:
			break;
		case Solo:
			break;
		case Switch:
			break;

		default:
			break;
		}
		iconAdapter.notifyDataSetChanged();
	}

	private boolean isZh() {
		Locale locale = getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		if (language.endsWith("zh"))
			return true;
		else
			return false;
	}

	/**
	 * 展示日期选择控件
	 * 
	 * @param dataStr
	 *            选择对话框title
	 * @param isYear
	 *            是否为年时间选择器
	 */
	private void showDateYearDialog(String dataStr, final boolean isYear) {
		// 用来获取日期和时间的
		Calendar calendar = Calendar.getInstance();

		Dialog dialog = null;
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				if (isYear) {
					expirationYear.setText(year + "");
				} else {
					String monthStr = month + 1 + "";
					if (monthStr.length() == 1) {
						expirationMoth.setText("0" + monthStr);
					} else {
						expirationMoth.setText(monthStr);
					}

				}

			}
		};
		dialog = new DataYearOrMonthPickerDialog(this, dateListener,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), dataStr);
		dialog.show();
		DatePicker dp = findDatePicker((ViewGroup) dialog.getWindow()
				.getDecorView());
		ViewGroup viewGroup = ((ViewGroup) (((ViewGroup) dp.getChildAt(0))
				.getChildAt(0)));
		View view0 = viewGroup.getChildAt(0);
		View view1 = viewGroup.getChildAt(1);
		View view2 = viewGroup.getChildAt(2);
		if (dp != null) {
			if (isZh()) {
				if (isYear) {
					// viewGroup.getChildAt(2).setVisibility(View.GONE);
					// viewGroup.getChildAt(1).setVisibility(View.GONE);
					if (null != view2) {
						view2.setVisibility(View.GONE);
					}
					if (null != view1) {
						view1.setVisibility(View.GONE);
					}
				} else {
					// viewGroup.getChildAt(0).setVisibility(View.GONE);
					// viewGroup.getChildAt(2).setVisibility(View.GONE);
					if (null != view0) {
						view0.setVisibility(View.GONE);
					}
					if (null != view2) {
						view2.setVisibility(View.GONE);
					}
				}
			} else {
				if (isYear) {
					// viewGroup.getChildAt(0).setVisibility(View.GONE);
					// viewGroup.getChildAt(1).setVisibility(View.GONE);
					if (null != view0) {
						view0.setVisibility(View.GONE);
					}
					if (null != view1) {
						view1.setVisibility(View.GONE);
					}
				} else {
					// viewGroup.getChildAt(1).setVisibility(View.GONE);
					// viewGroup.getChildAt(2).setVisibility(View.GONE);
					if (null != view1) {
						view1.setVisibility(View.GONE);
					}
					if (null != view2) {
						view2.setVisibility(View.GONE);
					}
				}
			}

		}
	}

	/**
	 * 从当前Dialog中查找DatePicker子控件
	 * 
	 * @param group
	 * @return
	 */
	private DatePicker findDatePicker(ViewGroup group) {
		if (group != null) {
			for (int i = 0, j = group.getChildCount(); i < j; i++) {
				View child = group.getChildAt(i);
				if (child instanceof DatePicker) {
					return (DatePicker) child;
				} else if (child instanceof ViewGroup) {
					DatePicker result = findDatePicker((ViewGroup) child);
					if (result != null)
						return result;
				}
			}
		}
		return null;
	}

	/**
	 * 显示选择日期的弹窗
	 */
	AlertDialog dateDialog;
	private ArrayList<Lines> lines;
	private String couponCode;
	private AddressModel addressModel = null;
	private String fromPage;

	public void showChooseDateDialog(final boolean isYear) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		ListView dateListView = new ListView(this);
		dateListView.setAdapter(new ChooseYearMonthListAdapter(this,
				isYear ? yearList : monthList));
		dateListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long positionId) {
				// 将选择的日期文本设置到相应的位置
				if (isYear) {
					String year = yearList.get(position);
					expirationYear.setText(year);
				} else {
					expirationMoth.setText(monthList.get(position));
				}
				dateDialog.dismiss();
			}
		});
		builder.setTitle(
				isYear ? R.string.creditcard_add_choose_year
						: R.string.creditcard_add_choose_month).setView(
				dateListView);
		dateDialog = builder.create();
		dateDialog.show();
		WindowManager.LayoutParams params = dateDialog.getWindow()
				.getAttributes();
		params.width = DpPxUtils.Dp2Px(AddCreditCardActivity.this, 200);
		params.height = DpPxUtils.Dp2Px(AddCreditCardActivity.this, 300);
		dateDialog.getWindow().setAttributes(params);
	}

	/**
	 * 信用卡Logo适配器
	 * 
	 * @author hf
	 * 
	 */
	class IconAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ccLogos.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup group) {
			HolderView holder;
			if (convertView == null) {
				holder = new HolderView();
				convertView = group.inflate(AddCreditCardActivity.this,
						R.layout.credit_card_icon_item, null);
				holder.iconImage = (ImageView) convertView
						.findViewById(R.id.icon_image);
				convertView.setTag(holder);
			} else {
				holder = (HolderView) convertView.getTag();
			}
			CreditCardLogoModel cclModel = ccLogos.get(position);
			if (null != cclModel) {
				boolean isSelected = cclModel.isSelected();
				if (isSelected) {
					holder.iconImage.setBackgroundResource(iconOnId[position]);
				} else {
					holder.iconImage.setBackgroundResource(iconId[position]);
				}
			}
			return convertView;
		}
	}

	class HolderView {
		// 帮助按钮
		ImageView iconImage;
	}

	/**
	 * @author tony 支付
	 */
	class PayTask extends BaseNeedReLoginTask {

		private CreditCardModel creditCardModel;
		private CreditCardPayRespose payRespose;

		public PayTask(CreditCardModel creditCardModel) {
			this.creditCardModel = creditCardModel;

		}

		@Override
		protected void onPreExecute() {
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... arg0) {
			try {
				payRespose = ProviderFactory.createCreditCardServiceProvider()
						.doCreditCardCheckout(
								ActivityUtil.getCustomerID() + "",
								ActivityUtil.getCustomerToken(), orderNumber,
								myAddress, false, isAddCard.isChecked(),
								creditCardModel, null, myAddress.getEmail());
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				hideAllLayout();
				if ("0".equals(result)) {
					// 支付完成，判断支付状态并跳转相应页面
					if (null != payRespose) {
						Intent goToPaymentFinish = new Intent(
								AddCreditCardActivity.this,
								PaymentCompleteActivity.class);
						goToPaymentFinish.putExtra("orderNumber", orderNumber);
						goToPaymentFinish.putExtra("payMoney",
								payRespose.getCurrencyCodeSymbol()
										+ (payRespose.getOrderTotal() + ""));
						goToPaymentFinish.putExtra("payMethod", "CreditCard");
						goToPaymentFinish.putExtra("cardType",
								cardType.toString());
						int responseResult = payRespose.getResponseResult();
						switch (responseResult) {
						case 0:
						case 3:
							// 支付成功
							goToPaymentFinish
									.putExtra(
											"payStatus",
											ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_SUCCESS);
							mesureTransaction(orderNumber,
									payRespose.getOrderTotal());
							break;
						case 1:
							// 支付失败
							goToPaymentFinish
									.putExtra(
											"payStatus",
											ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_FAILED);
							goToPaymentFinish.putExtra("errorCode",
									payRespose.getErroCode());
							break;
						case 2:
							// 待定
							goToPaymentFinish
									.putExtra(
											"payStatus",
											ServerConstant.ReturnCode.CreditCard.CREDITCARD_PAYSTATUS_PROCCESSING);
							break;

						default:
							break;
						}
						startActivity(goToPaymentFinish);
					}
				} else if(!isRelogin){
					// 出现异常，土司提示
					AlertToast.alert(AddCreditCardActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}
		}

		@Override
		protected Context setContext() {
			return AddCreditCardActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new PayTask(creditCardModel);
		}
	}

	/**
	 * 密码输入法
	 */
	private void showSecurityCodeDialog() {
		View dialogView = View.inflate(AddCreditCardActivity.this,
				R.layout.random_num_keybroad/* dialog_input */, null);
		securityCodeDialog = new AlertDialog.Builder(this).create();
		// dialog.setView(dialogView);
		securityCodeDialog.show();
		// 关键在下面的两行,使用window.setContentView,替换整个对话框窗口的布局
		Window window = securityCodeDialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		window.setContentView(dialogView);
		window.setWindowAnimations(R.style.KeybroadAnimation);
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
		// WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		ActivityUtil.intKeyboradView(dialogView, securityCode);
		final Button btn_conf = (Button) dialogView
				.findViewById(R.id.keyboard_btn_conf);
		btn_conf.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				securityCodeDialog.dismiss();
			}
		});
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(cardNumber.getWindowToken(), 0);
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (null != takePhotoPopWin && takePhotoPopWin.isShowing()) {
				takePhotoPopWin.dismiss();
			} else if (null != fromPage && "toPay".equals(fromPage)) {
				showConfirmGiveUpPayDialog();
			} else {
				finish();
			}
		}
		return true;
	}

	/**
	 *  GA衡量交易
	 */
	private void mesureTransaction(String orderNumber, double money) {
		ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder();
		if (null != lines && lines.size() != 0) {
			for (int i = 0; i < lines.size(); i++) {
				Lines line = lines.get(i);
				Product product = new Product()
						.setId(String.valueOf(line.getSku()))
						.setName(line.getName()).setQuantity(line.getQty())
						.setPrice(line.getSellingPrice());
				builder.addProduct(product);
			}
		}
		if (null != orderNumber) {
			ProductAction productAction = new ProductAction(
					ProductAction.ACTION_PURCHASE)
					.setTransactionId(orderNumber)
					// 此次交易关联的实体（例如某家商店）。
					.setTransactionAffiliation("DX Android Phone - Online")
					// 交易的总收入，含税费和运费。
					.setTransactionRevenue(money)
					// 交易的总税费。
					.setTransactionTax(0)
					// 交易的总运费。
					.setTransactionShipping(0)
					// 订单使用的Coupon
					.setTransactionCouponCode(couponCode);
			builder.setProductAction(productAction);

			theTracker.send(builder.build());
		}
	}

	// 银行卡号码的格式
	public void bankCardNumAddSpace(final EditText mEditText) {
		mEditText.addTextChangedListener(new TextWatcher() {
			int beforeTextLength = 0;
			int onTextLength = 0;
			boolean isChanged = false;

			int location = 0;// 记录光标的位置
			private char[] tempChar;
			private StringBuffer buffer = new StringBuffer();
			int konggeNumberB = 0;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				beforeTextLength = s.length();
				if (buffer.length() > 0) {
					buffer.delete(0, buffer.length());
				}
				konggeNumberB = 0;
				for (int i = 0; i < s.length(); i++) {
					if (s.charAt(i) == ' ') {
						konggeNumberB++;
					}
				}
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				onTextLength = s.length();
				buffer.append(s.toString());
				if (onTextLength == beforeTextLength || onTextLength <= 3
						|| isChanged) {
					isChanged = false;
					return;
				}
				isChanged = true;
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (isChanged) {
					location = mEditText.getSelectionEnd();
					int index = 0;
					while (index < buffer.length()) {
						if (buffer.charAt(index) == ' ') {
							buffer.deleteCharAt(index);
						} else {
							index++;
						}
					}

					index = 0;
					int konggeNumberC = 0;
					while (index < buffer.length()) {
						if ((index == 4 || index == 9 || index == 14 || index == 19)) {
							buffer.insert(index, ' ');
							konggeNumberC++;
						}
						index++;
					}

					if (konggeNumberC > konggeNumberB) {
						location += (konggeNumberC - konggeNumberB);
					}

					tempChar = new char[buffer.length()];
					buffer.getChars(0, buffer.length(), tempChar, 0);
					String str = buffer.toString();
					if (location > str.length()) {
						location = str.length();
					} else if (location < 0) {
						location = 0;
					}

					mEditText.setText(str);
					Editable etable = mEditText.getText();
					Selection.setSelection(etable, location);
					isChanged = false;
				}
			}
		});
	}

	/**
	 * 不同系统版本 不同隐藏软件盘方法
	 * @param ed
	 */
	public void hideSoftInputMethod(EditText ed) {
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		int currentVersion = android.os.Build.VERSION.SDK_INT;
		String methodName = null;
		if (currentVersion >= 16) {
			// 4.2
			methodName = "setShowSoftInputOnFocus";
		} else if (currentVersion >= 14) {
			// 4.0
			methodName = "setSoftInputShownOnFocus";
		}

		if (methodName == null) {
			ed.setInputType(InputType.TYPE_NULL);
		} else {
			Class<EditText> cls = EditText.class;
			Method setShowSoftInputOnFocus;
			try {
				setShowSoftInputOnFocus = cls.getMethod(methodName,
						boolean.class);
				setShowSoftInputOnFocus.setAccessible(true);
				setShowSoftInputOnFocus.invoke(ed, false);
			} catch (NoSuchMethodException e) {
				ed.setInputType(InputType.TYPE_NULL);
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
